package com.airena.controller;

import com.airena.result.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 文件上传
 */
@RestController
@Tag(name = "文件上传")
@RequestMapping("/upload")
@Slf4j
public class uploadController {

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @PostMapping
    public Result<String> uploadFile(MultipartFile file) throws Exception
    {
        log.info("文件上传:{}",file);
        try
        {
//            指定oss上传路径
            String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
//            上传图片,返回文件信息
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPath(format)
                    .upload();
            return Result.success(fileInfo == null ? "文件上传失败" : fileInfo.getUrl());
        }
        catch (Exception e)
        {
            log.error("文件上传失败",e);
            return Result.error("文件上传失败");
        }
    }
}
